﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.ServiceModel;
using System.Text.RegularExpressions;

namespace IssueVision.EntityModel
{
    /// <summary>
    /// User class validation logic
    /// </summary>
    public partial class User
    {
        /// <summary>
        /// Partial method to add all validation actions
        /// defined for this class
        /// </summary>
        partial void InitializeValidationSettings()
        {
#if SILVERLIGHT
            ValidateEntityOnPropertyChanged = false;
#endif
            AddPropertyValidationAction("Email", ValidateEmail);
        }

        #region "Private Validation Methods"

        /// <summary>
        /// Validation Action:
        /// check whether the email address is valid or not
        /// </summary>
        /// <param name="value"></param>
        private void ValidateEmail(object value)
        {
            string email = value as string;

            // user Email can be null
            if (email == null) return;
            // validate the e-mail format.
            if (Regex.IsMatch(email,
                   @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" +
                   @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$") == false)
            {
#if SILVERLIGHT
                ValidationResult result = new ValidationResult("Invalid email address.", new List<string> { "Email" });
                AddError("Email", result);
#else
                FaultReason faultReason = new FaultReason("Invalid email address.");
                throw new FaultException(faultReason);
#endif
            }
        }

        #endregion "Private Validation Methods"
    }
}